<template>
  <div class="app-container">
    <div class="search_wapper">
      <el-form ref="form" :model="form" size="small" label-width="100px">
        <el-row>
          <el-col :xs="24" :sm="24" :md="16" :lg="12" :xl="12">
            <el-form-item label="标签名称: " prop="name">
              <el-input v-model="form.name" placeholder="请输入标签名称" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="10" :lg="8" :xl="8">
            <el-form-item label="使用情况：" style="margin-left: 100px" prop="isUsed">
              <el-select v-model="form.isUsed" placeholder="全部">
                <el-option label="有内容在使用" value="1" />
                <el-option label="无" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="所属内容: " prop="useRules">
              <el-select
                v-model="tagList"
                style="width: 1000px"
                multiple
                placeholder="全部"
                @remove-tag="deleteTag"
              >
                <el-option
                  v-for="item in allRules"
                  :key="item.index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-button
            type="primary"
            @click="
              visible = true;
              type = true;
            "
          >+ 新建</el-button>
          <el-button @click="download">导出数据</el-button>
          <el-button style="float: right" @click="reset('form')">重置</el-button>
          <el-button type="primary" style="float: right" @click="check">查询</el-button>
        </el-row>
      </el-form>
    </div>
    <!-- 弹出新建标签框 -->
    <el-dialog
      :title="`${type === true ? '新建' : '修改'}运营标签`"
      width="980px"
      class="editModal"
      :visible.sync="visible"
      @closed="cancel"
    >
      <el-form ref="createForm" :model="createForm" :rules="rules">
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="标签名称" label-width="80px" prop="tagSingleName">
              <el-input
                autocomplete="off"
                maxlength="20"
                show-word-limit
                placeholder="请输入标签名称"
                v-model="createForm.tagSingleName"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="标签说明" label-width="80px">
              <el-input
                type="textarea"
                autocomplete="off"
                maxlength="50"
                show-word-limit
                placeholder="请输入标签说明"
                v-model="createForm.description"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <el-divider></el-divider>
      </el-row>
      <el-row>
        <h4>所属内容</h4>
      </el-row>
      <el-row>
        <el-table
          v-loading="listLoading"
          element-loading-text="Loading"
          :data="allRules"
          border
          fit
          :max-height="600"
          highlight-current-row
          style="margin-top: 30px"
          :header-cell-style="{
            background: '#d3d3d3',
            color: '#606266',
          }"
        >
          <el-table-column fixed prop="id" label="ID" align="center" width="100" v-if="false"></el-table-column>
          <el-table-column fixed align="center" label="所属内容" style="width: 500px" prop="name"></el-table-column>
          <el-table-column fixed align="center">
            <!-- :render-header="renderHeader" -->
            <template slot="header">
              <el-checkbox
                :indeterminate="isIndeterminate1"
                v-model="checkAll1"
                @change="handleCheckAllChange1"
              >是否启用</el-checkbox>
            </template>
            <template slot-scope="scope">
              <el-switch
                class="switchStyle"
                v-model="scope.row.stateIsStart"
                active-color="#409EFF"
                inactive-color="#909399"
                active-text="开"
                inactive-text="关"
                active-value="1"
                inactive-value="0"
                @change="switchIsStart($event, scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column align="center">
            <template slot="header">
              <el-checkbox
                :indeterminate="isIndeterminate2"
                v-model="checkAll2"
                @change="handleCheckAllChange2"
              >是否对外展示</el-checkbox>
            </template>
            <template slot-scope="scope">
              <el-switch
                class="switchStyle"
                v-model="scope.row.stateIsShow"
                active-color="#409EFF"
                inactive-color="#909399"
                active-text="开"
                inactive-text="关"
                active-value="1"
                inactive-value="0"
                :disabled="isDisabled"
                @change="switchIsShow($event, scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <div slot="footer" class="dialog-footer" align="center" style="margin-top: 30px">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="judge('createForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 表格内容 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :max-height="600"
      highlight-current-row
      style="margin-top: 30px"
      :header-cell-style="{ background: '#d3d3d3', color: '#606266' }"
      id="rebateSetTable"
    >
      <el-table-column fixed label="ID" align="center" width="100" v-if="false">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column fixed align="center" label="标签名称">
        <template slot-scope="scope">{{ scope.row.tagSingleName }}</template>
      </el-table-column>
      <el-table-column fixed label="标签说明" align="center">
        <template slot-scope="scope">{{ scope.row.description }}</template>
      </el-table-column>
      <el-table-column
        fixed
        label="所属内容"
        align="center"
        style="text-align: left"
        prop="useRules"
        :formatter="stateFormat"
      ></el-table-column>
      <el-table-column label="使用情况" align="center">
        <template slot-scope="scope">
          <span :style="scope.row.isUsed ? 'color: #20a0ff' : ''">
            <span v-if="scope.row.isUsed" @click="jump(scope.row)">有内容在使用</span>
            <span v-else>无</span>
          </span>
          <!-- {{ scope.row.isUsed ? `<span @click="jump">有内容在使用</span>` :
          "无" }}-->
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center">
        <template slot-scope="scope">{{ scope.row.createdBy }}</template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">{{ scope.row.createdAt }}</template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
          <!-- <el-button v-if="scope.row.auditStatus === 'Publish'" size="mini" :type="scope.row.onShelve ? 'danger' : 'primary'" @click="handleStaus(scope.row)">{{ scope.row.onShelve ? '下架' : '上架' }}</el-button> -->
          <el-button
            size="mini"
            type="danger"
            @click="handleDel(scope.row.id)"
            :disabled="scope.row.isUsed"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="page_count"
      background
      :page-sizes="[10, 20, 50, 100]"
      :page-size="queryData.pageSize"
      :current-page="queryData.pageNum"
      layout="total, prev, pager, next, jumper, sizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import {
  getTagList,
  delTag,
  getRules,
  addTag,
  editTag,
  downloadTemplate,
  detailTag
} from "@/api/newTag";
import FileSaver from "file-saver";
import XLSX from "xlsx";

export default {
  data() {
    return {
      form: {
        name: "",
        isUsed: "",
        useRules: "",
        treeId: 4
      },
      list: [],
      listLoading: false,
      loading: false,
      total: 10,
      totalPage: null,
      queryData: {
        pageSize: 10,
        pageNum: 1,
        sortBy: "createdAt",
        asc: false,
        treeId: 4
      },
      isDisabled: false,
      asyncFn: {},
      visible: false,
      createForm: {
        id: "",
        tagSingleName: "",
        description: "",
        isStart: [],
        isShow: []
      },
      rules: {
        tagSingleName: [
          { required: true, message: "请输入标签名称", trigger: "blur" }
        ]
      },
      allRules: [],
      tagList: "",
      type: "",
      editId: "",
      isIndeterminate1: false,
      checkAll1: false,
      isIndeterminate2: false,
      checkAll2: false
    };
  },
  created() {
    //  console.log('路由信息', this.$route)
    this.asyncFn.asyncGetList = getTagList;
    this.asyncFn.asyncDel = delTag;
    this.asyncFn.asyncGetRules = getRules;
    this.asyncFn.asyncAddTag = addTag;
    this.asyncFn.asyncEditTag = editTag;
    this.asyncFn.asyncDetailTag = detailTag;
    this.asyncFn.asyncDownloadTemplate = downloadTemplate;
    this.fetchData(this.queryData);
    this.getAllRules();
  },
  methods: {
    fetchData(data) {
      this.asyncFn.asyncGetList(data).then(res => {
        this.list = res.content;
        this.listLoading = false;
        this.totalPage = res.totalPage;
        this.total = res.total;
      });
    },
    stateFormat(row) {
      let res = row.useRules && Array.from(row.useRules);
      let arr = [];
      if (res) {
        res.forEach(element => {
          arr.push(this.allRules.filter(item => element == item.id)[0].name);
        });
      }
      return arr.join("、");
    },
    check() {
      this.form.useRules = this.tagList.join(",");
      this.queryData.pageSize = 10;
      this.queryData.pageNum = 1;
      let obj = Object.assign(this.queryData, this.form);
      this.fetchData(obj);
    },
    reset(formName) {
      this.$refs[formName].resetFields();
    },
    deleteTag() {
      this.form.useRules = this.tagList.join(",");
      this.fetchData(this.form);
    },
    handleEdit(id) {
      this.asyncFn.asyncDetailTag(id).then(res => {
        this.visible = true;
        this.type = false;
        this.createForm.tagSingleName = res.name.split(":")[1];
        this.createForm.description = res.description;
        this.editId = res.id;
        //useRule
        this.createForm.isStart = res.useRules == null ? [] : res.useRules;
        this.createForm.isShow = res.exposeRules == null ? [] : res.exposeRules;

        if (res.useRules) {
          res.useRules.forEach(item => {
            this.allRules.forEach(ele => {
              if (ele.id == item) {
                ele.stateIsStart = "1";
              }
            });
          });
        }
        if (res.exposeRules) {
          res.exposeRules.forEach(item => {
            this.allRules.forEach(ele => {
              if (ele.id == item) {
                ele.stateIsShow = "1";
              }
            });
          });
        }

        let len = this.createForm.isStart.length;
        if (len == 8) {
          this.isIndeterminate1 = false;
          this.checkAll1 = true;
        } else if (len > 0 && len < 8) {
          this.isIndeterminate1 = true;
        } else {
          this.isIndeterminate1 = false;
          this.checkAll1 = false;
        }
        let len2 = this.createForm.isShow.length;
        if (len2 == 8) {
          this.isIndeterminate2 = false;
          this.checkAll2 = true;
        } else if (len2 > 0 && len2 < 8) {
          this.isIndeterminate2 = true;
        } else {
          this.isIndeterminate2 = false;
          this.checkAll2 = false;
        }
      });
    },
    commitEdit() {
      let obj = {};
      obj.name = "运营:" + this.createForm.tagSingleName;
      obj.description = this.createForm.description;
      obj.treeId = 4;
      obj.useRules = this.createForm.isStart;
      obj.exposeRules = this.createForm.isShow;
      //校验是否启用和对外展示
      let flag = true;
      obj.exposeRules.forEach(expose => {
        if (!obj.useRules.includes(expose)) {
          flag = false;
        }
      });
      if (flag) {
        this.asyncFn
          .asyncEditTag(this.editId, obj)
          .then(res => {
            this.$message.success({
              message: "修改成功"
            });
            this.visible = false;
            this.$router.go(0);
            this.createForm = {};
          })
          .catch(err => {
            // console.log("操作错误", err);
            this.$message.error({
              message: "操作失败"
            });
          });
      } else {
        this.$message.error({
          message: "标签启用后才能对外显示，请检查参数"
        });
      }
    },
    judge(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.type == true) {
            this.add();
          } else {
            this.commitEdit();
          }
        } else {
          return false;
        }
      });
    },
    handleDel(id) {
      this.$confirm(
        `此操作会删除标签相关的所有数据，是否选择继续操作删除？`,
        "删除标签",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error"
        }
      ).then(() => {
        // const loading = this.$loading({
        //   text: '提交中...'
        // })
        // this.loading = true
        // console.log(id);
        this.asyncFn
          .asyncDel(id)
          .then(res => {
            this.$router.go(0);
            this.$message.success({
              message: "删除成功"
            });
          })
          .catch(err => {
            this.$message.error({
              message: "删除失败"
            });
          });
      });
    },
    handleSizeChange(val) {
      this.queryData.pageSize = val;
      this.fetchData(this.queryData);
    },
    handleCurrentChange(val) {
      this.queryData.pageNum = val;
      this.fetchData(this.queryData);
    },
    getAllRules() {
      this.asyncFn.asyncGetRules().then(res => {
        res.forEach(ele => (ele.stateIsStart = "0"));
        res.forEach(ele => (ele.stateIsShow = "0"));

        this.allRules = res;
        // this.createTable = this.allRules;
        // ？？？
      });
    },
    switchIsStart(val, row) {
      if (val == 1) {
        this.createForm.isStart.push(row.id);
      } else {
        this.createForm.isStart = this.createForm.isStart.filter(
          item => item !== row.id
        );
      }
      //console.log(this.createForm.isStart);
      let len = this.createForm.isStart.length;
      //console.log(len);
      if (len == 8) {
        this.isIndeterminate1 = false;
        this.checkAll1 = true;
      } else if (len > 0 && len < 8) {
        this.isIndeterminate1 = true;
      } else {
        this.isIndeterminate1 = false;
        this.checkAll1 = false;
      }
    },
    switchIsShow(val, row) {
      //只有启用了才可以对外显示
      if (val == 1) {
        this.createForm.isShow.push(row.id);
      } else {
        this.createForm.isShow = this.createForm.isShow.filter(
          item => item !== row.id
        );
      }
      let len = this.createForm.isShow.length;
      if (len == 8) {
        this.isIndeterminate2 = false;
        this.checkAll2 = true;
      } else if (len > 0 && len < 8) {
        this.isIndeterminate2 = true;
      } else {
        this.isIndeterminate2 = false;
        this.checkAll2 = false;
      }
    },
    add() {
      let obj = {};
      obj.name = "运营:" + this.createForm.tagSingleName;
      obj.treeId = 4;
      obj.description = this.createForm.description;
      obj.useRules = this.createForm.isStart ? this.createForm.isStart : "";
      obj.exposeRules = this.createForm.isShow ? this.createForm.isShow : "";
      // console.log(obj);
      this.asyncFn
        .asyncAddTag(obj)
        .then(res => {
          this.visible = false;
          this.$router.go(0);
          // ??？
          this.createForm = "";
          this.$message.success({
            message: "添加成功"
          });
        })
        .catch(err => {
          // console.log("操作错误", err);
          this.$message.error({
            message: "操作失败"
          });
        });
    },
    renderHeader(h, { column }) {
      return h("div", [
        h("span", column.label),
        h("el-checkbox", {
          style: "display:inline-flex;margin-left:20px;",
          on: {
            change: ($event, column) => {
              //console.log(column);
              //this.select($event, column)
            }
          },
          props: {
            indeterminate: false
            // value: this.data.checkAll,
          }
        })
      ]);
    },
    handleCheckAllChange1(val) {
      if (val == true) {
        this.allRules.forEach(item => {
          item.stateIsStart = "1";
          if (this.createForm.isStart.indexOf(item.id) == -1) {
            this.createForm.isStart.push(item.id);
          }
        });
      } else {
        this.allRules.forEach(item => {
          console.log(item);
          item.stateIsStart = "0";
          this.createForm.isStart = this.createForm.isStart.filter(
            ele => ele !== item.id
          );
        });
      }
      this.isIndeterminate1 = false;
      //console.log( this.createForm.isStart)
    },
    handleCheckAllChange2(val) {
      if (val == true) {
        this.allRules.forEach(item => {
          item.stateIsShow = "1";
          if (this.createForm.isShow.indexOf(item.id) == -1) {
            this.createForm.isShow.push(item.id);
          }
        });
      } else {
        this.allRules.forEach(item => {
          item.stateIsShow = "0";
          this.createForm.isShow = this.createForm.isShow.filter(
            ele => ele !== item.id
          );
        });
      }

      this.isIndeterminate2 = false;
      //console.log(this.createForm.isShow);
      // console.log(this.allRules);
    },
    download() {
      let obj = {
        sortBy: "createdAt",
        asc: false,
        treeId: 4,
        ...this.form
      };
      this.asyncFn.asyncDownloadTemplate(obj);
    },
    cancel() {
      this.$refs["createForm"].clearValidate();
      this.visible = false;
      this.createForm = {
        id: "",
        tagSingleName: "",
        description: "",
        isStart: [],
        isShow: []
      };
      this.checkAll1 = false;
      this.checkAll2 = false;
      this.isIndeterminate1 = false;
      this.isIndeterminate2 = false;
      this.allRules.forEach(item => {
        item.stateIsStart = "0";
        item.stateIsShow = "0";
      });
    },
    jump(row) {
      console.log(row.tagSingleName);
      this.$router.push({
        path: "/content/content",
        query: {
          operationLabel: row.tagSingleName
        }
      });
    }
    /*observer(target, params) {
      let handler = {
        set(target, key, value, receiver) {
          this.allRules.forEach((item) => {
            item.params = "0";
          });
          for (i = 0; i < target.length; i++) {
            for (i = 0; i < this.allRules.length; i++) {
              if (this.allRules[i].id == target[i]) {
                this.allRules[i].params = "1";
              }
            }
          }
          return Reflect.set(target, key, value, receiver);
        },
      };
      return new Proxy(target, handler);
    },*/
  }
};
</script>

<style lang="scss">
.app-container {
  overflow: hidden;
  padding-bottom: 30px;
  ::v-deep thead {
    color: #606266;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #409eff;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  ::v-deep .el-table .cell {
    line-height: normal;
  }
  .page_count {
    margin-top: 30px;
    float: right;
  }
  ::v-deep .el-pagination__sizes {
    margin-left: 20px;
  }
  .editModal {
    ::v-deep .el-dialog__body {
      padding: 30px 30px 0px 20px;
    }
  }
  .el-divider--horizontal {
    margin: 8px 0;
    background: 0 0;
    border-top: 2px dashed #a9a9a9;
  }

  .switchStyle .el-switch__label {
    position: absolute;
    display: none;
    color: #fff;
  }
  .switchStyle .el-switch__label--left {
    z-index: 1;
    left: 6px;
  }
  .switchStyle .el-switch__label--right {
    z-index: 1;
    left: -14px;
  }
  .switchStyle .el-switch__label.is-active {
    display: block;
  }
  .switchStyle.el-switch .el-switch__core,
  .el-switch .el-switch__label {
    width: 50px !important;
  }
}
</style>
